package com.example.chapterredis.common.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;

/**
 * @author tony
 */
@Configuration
public class RedisConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(RedisConfiguration.class);

    @Value("${spring.redis.clusterNodes}")
    private String  clusterNodes;
    @Value("${spring.redis.password}")
    private String  auth;
    @Value("${spring.redis.pool.maxActive}")
    private Integer maxTotal;
    @Value("${spring.redis.pool.minIdle}")
    private Integer minIdle;
    @Value("${spring.redis.pool.maxIdle}")
    private Integer maxIdle;
    @Value("${spring.redis.pool.maxWait}")
    private Long    maxWaitMillis;
    @Value("${spring.redis.pool.commandTimeout}")
    private int     commandTimeout;


    @Bean
    public JedisCluster jedisCluster() {
        String[] serverArray = clusterNodes.split(",");
        Set<HostAndPort> nodes = new HashSet<>();
        for (String ipPort : serverArray) {
            String[] ipPortPair = ipPort.split(":");
            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
        }

        if (!nodes.isEmpty()) {
            String password = getAuth(auth);
            logger.info("redis password:{}", password);
            GenericObjectPoolConfig pool = new GenericObjectPoolConfig();
            pool.setMaxTotal(maxTotal);
            pool.setMinIdle(minIdle);
            pool.setMaxIdle(maxIdle);
            pool.setMaxWaitMillis(maxWaitMillis);
            return new JedisCluster(nodes, commandTimeout, commandTimeout, 5, password, pool);
        }
        return null;
    }

    private String getAuth(String auth) {
        return "".equals(auth) ? null : auth;
    }
}
